<template>
<form @submit="formSubmit" class='repair-form' report-submit>
  <div class="repairContainer">
        <div class='form-wrap'>
           <scroll-view style='height:100%;' :scroll-y="true" @scrolltolower="scrolltolower" @scroll="scroll" >
              <div class='info-title'>
                <image src='/static/images/repair_icon_build@3x.png'/>
                <span>建筑设备</span>
                <div class='scanCode' @click.stop='scanCode'>
                  <image src='/static/images/nav_scan_blue_b@3x.png'/>
                </div>
              </div>
              <div class='info-wrap'>
                <div class='info-line'>
                  <div class='info-label label-type'>工单类型：</div>
                  <div class='info-content'>
                    <i-row i-class='btn-line'>
                      <i-col span="8">
                        <button @click="changeOrderType(0)" class='type-btn' :class='{active:orderType==0}'>故障</button>
                      </i-col>
                      <i-col span="8" offset='1'>
                        <button @click="changeOrderType(3)" class='type-btn' :class='{active:orderType==3}'>事务</button>
                      </i-col>
                    </i-row>
                  </div>
                </div> 
                <div class='info-line' @click.stop="toPage('repair_project')">
                  <div class='info-label'>项目建筑：</div>
                  <div class='info-content'>
                    <div class='project-name'>{{projectName}}</div>
                    <div class='building-name'>{{buildingName}}</div>
                  </div>
                  <div class='arrow-right'>
                    <i-icon type="enter" size="20" color="#c9d7db" />
                  </div>
                </div>
                <div class='info-line'>
                  <div class='info-label'>设备/区域：</div>
                  <div class='mr10'>
                    <i-switch :value="switch1" size="large"  @change="onChange" slot="footer">
                        <view slot="open">设备</view>
                        <view slot="close">区域</view>
                    </i-switch>
                  </div>
                </div>
                <div class='info-line' @click.stop="toPage('repair_device')" v-if='switch1'>
                  <div class='info-label'>设备名称：</div>
                  <div class='info-content'>
                    <div class='project-name'>{{deviceName}}</div>
                  </div>
                  <div class='arrow-right'>
                    <i-icon type="enter" size="20" color="#c9d7db" />
                  </div>
                </div>
                <div class='info-line' @click.stop="toPage('repair_area')" v-else>
                  <div class='info-label'>区域名称：</div>
                  <div class='info-content'>
                    <div class='project-name'>{{areaName}}</div>
                  </div>
                  <div class='arrow-right'>
                    <i-icon type="enter" size="20" color="#c9d7db" />
                  </div>
                </div>
                <div class='info-line'>
                  <div class='info-label'>优先级：</div>
                  <div class='mr10'>
                    <i-switch :value="priority" size="large"  @change="onChangepriority" slot="footer">
                        <view slot="open">紧急</view>
                        <view slot="close">正常</view>
                    </i-switch>
                  </div>
                </div>
                <div class='info-line nobottom'>
                  <div class='info-label label-type'>问题类型：</div>
                  <div class='info-content'>
                    <i-row i-class='btn-line'>
                      <i-col span="8" v-for='(btn,index) in faultTypeList' :key='index'>
                        <button @click="changeFaultType(btn.id)" class='type-btn' :class='{active:faultTypeId==btn.id,m20:index>2}'>{{btn.name}}</button>
                      </i-col>
                    </i-row>
                  </div>
                </div> 
              </div>
              <div class='info-title'>
                <image src='/static/images/repair_icon_photo@3x.png'/>
                <span>现场照片</span>
              </div>
              <div class='info-wrap'>
                <!-- <i-row>
                      <mp-uploader ref="uploader" @upLoadSuccess="upLoadSuccess" @upLoadFail="upLoadFail" @uploadDelete="uploadDelete" :showTip=true :count=3 :maxLength=3></mp-uploader>
                      <i-col span="6" i-class='camera-wrap'>
                        <i-icon type="camera" color='#0886d5' size='34' />
                      </i-col>
                </i-row> -->
                  <div class='weui-uploader__bd p10'>
                     <div class="weui-uploader__files" id="uploaderFiles">
                        <block v-for="(item,index) in files" :key="index">
                          <div class="weui-uploader__file camera-wrap image-wrap" @click="previewImage($event,index)" :id="item">
                            <i-icon type="delete_fill" i-class='del-btn' @click.stop="deletImg(index)" size='24' color='#da1e2f'/>
                            <image class="weui-uploader__img" :src="item" mode="aspectFit" />
                          </div>
                        </block>
                      </div>
                      <div class='camera-wrap' @click="chooseImage">
                          <img src='/static/images/repair_btn_photo@3x.png' class='camera-wrap-img'/>
                      </div>
                  </div>
                  
              </div>  
              <div class='info-title'>
                <image src='/static/images/repair_icon_describe@3x.png'/>
                <span>故障描述</span>
              </div>
              <div class='info-wrap'>
                <i-row>
                      <i-col span="24" i-class='desc-wrap'>
                        <textarea placeholder="不超过100个字" class='desc' v-model='comment'/>
                      </i-col>
                </i-row>
              </div>
          </scroll-view>
        </div>
        <i-row i-class='submit-line'>
            <button formType="submit" class='submit-btn'>报修</button>
        </i-row>
  </div>
  <i-toast id="toast" />
  </form>
</template>

<script type="text/javascript">
import { mapState } from 'vuex';
import mpUploader from 'mpvue-weui/src/uploader';
import { $Toast } from '@/../static/iview/base/index';
export default {
  data() {
    return {
      switch1 : false,
      priority:false,
      files: [],
      filesOnline: [],
      faultTypeList:[],
      orderType:0,
      faultTypeId:'',
      buildingName:'',
      buildingId:'',
      projectId:'',
      projectName:'',
      zoneId:'',
      areaName:'',
      deviceName:'',
      deviceId:'',
      faultPos:'',
      deviceNum:'',
      comment:''
    }
  },
  onShow(){
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1]; //当前页面
    var params = currPage.data;
    if(params.buildingName) this.buildingName = params.buildingName;
    if(params.projectName) this.projectName = params.projectName;
    this.zoneId = params.zoneId || '';
    this.areaName = params.areaName || '';
    this.deviceId = params.deviceId || '';
    this.deviceName = params.deviceName || '';
    if(params.faultPos) this.faultPos = params.faultPos;
    if(params.deviceNum) this.deviceNum = params.deviceNum;
    if(params.projectId) this.projectId = params.projectId;
    if(params.buildingId) this.buildingId = params.buildingId;
  },
  beforeMount() {
    this.findFaultType()
  },
  onLoad(){
    Object.assign(this.$data, this.$options.data())
  },
  components: {
    mpUploader
  },
  computed:{
    ...mapState(['userInfo']),
  },
  methods:{
    onChange(event){
        const value = event.mp.detail.value;
        this.switch1 = value;
    },
    onChangepriority(event){
        const value = event.mp.detail.value;
        this.priority = value;
    },
    changeOrderType(type){
      this.orderType = type
    },
    changeFaultType(type){
      this.faultTypeId = type
    },
    upLoadSuccess(successRes){
      console.log('successRes',successRes)
    },
    upLoadFail(failRes){
      console.log('failRes',failRes)
    },
    uploadDelete(DeleteRes){
      console.log('DeleteRes',DeleteRes)
    },
    chooseImage(e) {
      var _this = this;
      if(_this.files.length == 3){
        $Toast({
            content: '图片最多上传三张'
        });
        return;
      }
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          _this.files = _this.files.concat(res.tempFilePaths)
          
          //var tempFilePaths = res.tempFilePaths
          // console.log(tempFilePaths)
          
          /* wx.getFileSystemManager().readFile({
            filePath: tempFilePaths[0], //选择图片返回的相对路径
            encoding: 'base64', //编码格式
            success: res => { //成功的回调
              //_this.filesOnline = _this.filesOnline.concat(JSON.parse(res.data).data)
              //'data:image/png;base64,' + 
              _this.filesOnline.push(res.data)
            }
          }) */
          
        },
        fail: function () {
          console.log('fail');
        },
        complete: function () {
          console.log('commplete');
        }
      })
    },
    uploadImg(orderId){
      var _this = this;
      this.files.map(item=>{
          this.$http.upload({
            header: {  
              "Content-Type": "multipart/form-data"  
            },
            url: '/order/uploadImg',
            file: item,
            data:{
              ukey: _this.userInfo.ukey,
              userId: _this.userInfo.userId,
              orderId,
              type:0
            }
          }).then(res=>{
            if(res.statusCode==200){
              _this.filesOnline = _this.filesOnline.concat(JSON.parse(res.data))
              console.log('_this.filesOnline',_this.filesOnline)
            }
          }).catch(e=>{
            console.log('获取错误',e)
          })
        })
    },
    previewImage(e) {
      wx.previewImage({
        current: e.currentTarget.id, // 当前显示图片的http链接
        urls: this.files // 需要预览的图片http链接列表
      })
    },
    deletImg(index){
      this.files.splice(index,1)
      this.filesOnline.splice(index,1)
    },
    scanCode(){
      var _this = this;
      wx.scanCode({
        success(res){
          if(res.errMsg=='scanCode:ok'){
            var data = JSON.parse(res.result);
            if(data.type==1){
              _this.switch1 = false
              _this.queryZone(data.id)
            }else if(data.type==0){
              _this.switch1 = true;
              _this.queryDevice(data.id)
            }
          }
        }
      })
    },
    queryZone(id){
     this.$http.post({
       url:'/project/getZone',
       data:{
         ukey:this.userInfo.ukey,
         userId: this.userInfo.userId,
         zoneId:id
       }
     }).then(res=>{
       if(res.s==0){
            this.projectId = res.i.Data.projectId;
            this.projectName = res.i.Data.projectName;
            this.buildingId = res.i.Data.buildingId;
            this.buildingName = res.i.Data.buildingName;
            this.zoneId = res.i.Data.zoneId;
            this.areaName = res.i.Data.zoneName;
            this.faultPos = res.i.zonePos;
       }
     })
    },
    queryDevice(id){
     this.$http.post({
       url:'/project/getDevice',
       data:{
         ukey:this.userInfo.ukey,
         userId: this.userInfo.userId,
         accountId:id
       }
     }).then(res=>{
       if(res.s==0){
            this.projectId = res.i.Data.projectId;
            this.projectName = res.i.Data.projectName;
            this.buildingId = res.i.Data.buildingId;
            this.buildingName = res.i.Data.buildingName;
            this.deviceId = res.i.Data.accountId;
            this.faultPos = res.i.Data.devicePos;
            this.deviceName = res.i.Data.deviceTypeName;
            this.deviceNum = res.i.Data.deviceNum;
            
       }
     })
    },
    toPage(page){
      var url = `/pages/${page}/main`;
      if(page=='repair_area' || page=='repair_device'){
        if(this.buildingId==''){
          $Toast({
              content: '摩派：请先选择建筑'
          });
          return;
        }
        url+=`?buildingId=${this.buildingId}`
      }
      wx.navigateTo({
        url
      })
    },
    findFaultType(){
      this.$http.post({
        url:'/order/getAllFaultTypes',
        data:{
          ukey:this.userInfo.ukey,
        }
      }).then(res=>{
        if(res.s==0){
          this.faultTypeList = res.i.Data;
          this.faultTypeId = this.faultTypeList[0].id;
        }
      }).catch(e=>{
        console.log('获取失败')
      })
    },
    formSubmit(){
      var _this = this;
      var data = {
          ukey:this.userInfo.ukey,
          userId:this.userInfo.userId,
          projectId:this.projectId,
          priority:this.priority?1:0,
          buildingId:this.buildingId,
          orderType:this.orderType,
          faultType:this.switch1?0:1,
          faultTypeId:this.faultTypeId,
          faultId:this.switch1?this.deviceId:this.zoneId,
          faultPos:this.faultPos,
          deviceInfo:this.switch1?this.deviceName+'/'+this.deviceNum:this.faultPos,
          comment:this.comment,
          type:0
      };
      var url = '/order/createFaultOrder2';
      this.$http.post({url,data}).then(res=>{
        if(res.s==0){
          if(this.files.length>0){
            this.uploadImg(res.i.Data.orderId)
          }
          $Toast({
            content:'报修成功'
          });
          wx.navigateBack({delta:2})
        }
      }).catch(e=>{
        console.log('报修失败',e)
      })
    }
  }
}
</script>

<style lang='less'>
page{
  height:100%;
  background:#eef7fd;
}
::-webkit-scrollbar{
  width: 0;
  height: 0;
  color: transparent;
}
.repair-form{
  height: 100%
}
.repairContainer{
    height:100%;
    display: flex;
    flex-direction: column;
    .form-wrap{
      flex:1;
      height:50rpx;
      .scanCode{
        float: right;
        width: 40rpx;
        height: 40rpx;
        margin-right:20rpx; 
        image{
          width: 100%;
          height: 100%;
          margin: 0!important
        }
      }
      .info-title{
        height: 90rpx;
        line-height: 90rpx;
        font-size:32rpx;
        color:#83878a;
        image{
          width:30rpx;
          height: 30rpx;
          vertical-align: middle;
          margin:-10rpx 20rpx 0 30rpx 
        }
      }
      .info-wrap{
        display: flex;
        flex-direction: column;
        margin:0 20rpx;
        border:1px solid #ddd;
        border-radius:8rpx;
        background: #fff;
        .info-line{
          display: flex;
          justify-content:space-between;
          line-height:60rpx;
          padding: 10rpx 0;
          border-bottom:1px solid #dfe3e5;
          &.nobottom{
            border-bottom:none;
          }
        }
        .info-label{
          font-size:30rpx;
          color: #8a8a8a;
          margin-left:20rpx; 
          &.label-type{
            align-self:center;
          }
        }
        .info-content{
          flex:1;
          padding-left:20rpx; 
          .btn-line{
            width:90%;
            margin: 20rpx;
          }
          .project-name{
            color:#4d92c2;
            font-size:32rpx;
          }
          .building-name{
            font-size:28rpx;
          }
          .type-btn{
            height: 60rpx;
            line-height: 60rpx;
            border:2rpx solid #e7e7e9;
            border-radius:44rpx;
            font-size:26rpx;
            padding:0;
            background: #fff;
            margin-right:16rpx;
            &.m20{
              margin-top: 16rpx;
            }
            &::after{
               border: none
            }
            &.active{
              border:2rpx solid #4d92c2!important;
              color:#4d92c2!important;
            }
            
          }
        }
        .arrow-right{
          align-self: center;
          margin-right:20rpx; 
        }
        .desc-wrap{
          display: flex;
        }
        .desc{
          flex:1;
          padding: 16rpx;
          height:140rpx;
        }
        .camera-wrap{
          float: right;
          width: 120rpx;
          height: 120rpx;
          border-radius:16rpx; 
          margin:0 16rpx;
          background: #f0f6f6;
          display: flex;
          align-items: center;
          justify-content: center;
          .camera-wrap-img{
            width: 54rpx;
            height: 54rpx;
          }
        }
        .image-wrap{
          float: left;
          position: relative;
          margin-left:0; 
          .del-btn{
            position:absolute;
            right: -16rpx;
            top:-16rpx;
          }
        }
        .p10{
          padding: 20rpx;
        }
        .weui-uploader__img{
          width: 120rpx;
          height: 120rpx;
          border-radius:16rpx; 
        }
      }
    }
    .mr10{
      margin-right:30rpx; 
    }
    .submit-line{
      margin:50rpx 0; 
      .submit-btn{
        width:70%;
        background: #1380d3;
        color:#fff!important;
        font-size:36rpx;
        border-radius:40rpx; 
        height: 80rpx;
        line-height: 80rpx;
      }
    }
  }
  
</style>
